import './home.styl'
import {Button, Form, Input, InputNumber, Modal, Popconfirm, Radio, Space, Table, theme} from "antd";
import {useEffect, useRef, useState} from "react";
import {getListApi} from "../../interface/typeApi";
import {useOutletContext} from "react-router-dom";
import {isEmpty, useMsg} from "../../common/utils/toolUtil";
import {MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
function Home() {
    //接收到的内容
    const { content } = useOutletContext();
    // 提示弹窗的定义 useModal 和 contextHolder
    const [modal, contextHolder] = Modal.useModal();
    //消息弹窗
    const { isMsg, msgTitle} = useMsg();
    // 提示弹窗调用方法
    function info(val){
        modal.info({
            title: '温馨提示!',
            okText: '确定',
            content: <div>{val}</div>,
            onOk:handMsgOk
        });
    }
    //如果接受到数据就执行调用接口
    useEffect(()=>{
        if(content){
            queryListFun()
        }
    },[content])
    const [tableData, setTableData] = useState([])
    const [tableDataCopy, setTableDataCopy] = useState([])
    const [tableHeight, setTableHeight] = useState(0);
    useEffect(()=>{
        queryListFun()
        const handleResize = () => {
                // 减去可能的头部高度和其他padding/margin
                const height = document.body.clientHeight - 290;
                setTableHeight(height);
                queryListFun()
        };
        // 初始计算
        handleResize();
        // 添加窗口resize监听
        window.addEventListener('resize', handleResize);
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    },[])
    // 创建路由钩子
    const [columns, setColumns] = useState([
        { title: '名称',key:'1', dataIndex: 'name',align:'center' },
        { title: '选项',key:'2', dataIndex: 'itemList',align:'center',render:(text,record)=>{
          return <div>{text.toString()}</div>
        }
        },
        { title: '类型',key:'3', dataIndex: 'type',align:'center' },
        { title: '排序',key:'4', dataIndex: 'sort',align:'center' },
        { title: '操作',key:'operation', fixed: 'right',width: 160,align:'center', render: (text,record) =>
                <div className='flex w-full justify-evenly'>
                    <Button type="primary" size='small' onClick={()=>submitFun(record,'','edit')}  htmlType="submit">编辑</Button>
                    <Popconfirm
                        title="温馨提示"
                        description="是否确认执行删除该数据?"
                        onConfirm={() => { submitFun(record, '', 'delete') }} // 移除了参数val，直接传递record
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="primary" danger size='small' htmlType="submit">删除</Button>
                    </Popconfirm>
                </div>
        },
    ])
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [typeList, setTypeList] = useState([{ value: '1', label: '单选' },{ value: '2', label: '多选' },{ value: '3', label: '文本' }]);
    const token = theme.useToken().token || {};
    const onSelectChange = newSelectedRowKeys => {
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const [formRef] = Form.useForm();
    const [form, setForm] = useState({})
    const [keyword, setKeyword] = useState('')
    const keywordRef = useRef("");
    const [modalTitle, setModalTitle] = useState('');
    const [isModalOpen, setIsShowModal] = useState(false);
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    function handMsgOk(val){
        //执行删除
        const newData = tableData.filter(item => !selectedRowKeys.includes(item.id));
        setTableData(newData);
        setSelectedRowKeys([]);
        return new Promise(resolve => resolve(true));
    }
    function submitFun(values, errorFields, type) {
      switch (type) {
           case 'add':
              setModalTitle('新增详情');
              setIsShowModal(true);
              formRef.resetFields();
              formRef.setFieldsValue({
                  id:  tableData.length + 1,
                  name:'',
                  itemList: [],
                  sort: 1,
                  type: "1",
              })
           break;
           case 'edits':
               if (selectedRowKeys.length<=0) {
                   isMsg({code:400,msg:'请选择一条数据!'})
                   return;
               }else if (selectedRowKeys.length>=2){
                   isMsg({code:400,msg:'只能对一条数据进行编辑!'})
                   return;
               }
               setModalTitle('编辑详情项');
               setIsShowModal(true);
               let row = tableData[selectedRowKeys[0]];
               setForm(row);
               formRef.setFieldsValue(row)
               break;
           case 'edit':
              setModalTitle('编辑详情项');
              setIsShowModal(true);
              formRef.setFieldsValue(values);
              console.log(values)
              setForm(values)
              break;
           case 'deletes':
               info('是否执行删除选中的'+selectedRowKeys.length+'条数据?')
              break;
           case 'delete':
               if (values.id) {
                   //模拟删除数据
                   setTableData(prevData => prevData.filter(item => item.id !== values.id));
               }
              break;
      }
    }
    function queryListFun(){
        if(!content){
            return
        }
        localStorage.setItem('tokenCss',JSON.stringify(token));
        getListApi({},{id:content.id}).then(res=>{
            if (res.code === 200) {
                setTableData(res.data.records || []);
                setTableDataCopy(res.data.records || [])
            }
        })
    }
    function searchFun(){
        if (isEmpty(keywordRef.current)) {
            setTableData(tableDataCopy);
        }else {
            const result = tableData.filter(item => {
                return Object.values(item).some(val => val?.toString().includes(keywordRef.current));
            });
            setTableData(result);
        }
    }
    //监听值
    useEffect(()=>{
        keywordRef.current = keyword;
       if(!keyword){
           searchFun()
       }
    },[keyword])
    function onFinish(){
        console.log("提交表单了")
        formRef.validateFields().then((valid) => {
            if(valid){
                console.log("表单通过了")
                if(modalTitle==='新增详情'){
                    let formData = formRef.getFieldsValue();
                    console.log(formData)
                    setTableData([...tableData,formData])
                    setIsShowModal(false)
                }else {
                    if (form.id){
                        let formData = formRef.getFieldsValue();
                        let newList = [];
                        tableData.map(item=>{
                            if (item.id === form.id){
                                return formData
                            }
                            return item
                        })
                        setTableData(newList)
                        setIsShowModal(false)
                    }
                }
            }
        } ).catch((error) => {
            console.log("表单验证失败", error);
        });
    }
    return (
        <div className="w-full h-full" >
            <div style={{backgroundColor:token.colorBgContainer}} className='h-14 flex w-full items-center justify-between'>
                <div className='flex items-center'>
                    <div className='ml-2'>{content.name}</div>
                    {content.status === 1 && <span style={{color:token.colorPrimaryText,backgroundColor:token.colorPrimaryBg,marginLeft:'10px',padding:'2px 4px',borderRadius:'4px'}}>已启用</span>}
                    {content.status === 0 && <span style={{color:'#ff1631',backgroundColor:'#E8F4FF',marginLeft:'10px',padding:'2px 4px',borderRadius:'4px'}}>已禁用</span>}
                    <div className='ml-2 flex items-center'>
                        <span>类别详情</span>
                        <div>{tableData.length || 0}</div>
                        <div>项</div>
                    </div>
                </div>
                <div className='mr-5'>
                    <Input.Search
                        allowClear
                        onChange={(value)=>setKeyword(value.target.value)}
                        value={keyword}
                        onSearch={searchFun}
                        onPressEnter={searchFun}
                        placeholder="请输入搜索内容" style={{width:'200px',marginRight:'10px'}}/>
                    <Button type="default" style={{ borderRadius:'6px 0 0 6px'}} onClick={()=>{submitFun('','','add')}}>新增</Button>
                    <Button type="default" style={{ borderRadius:'0'}} onClick={()=>{submitFun('','','edits')}}>编辑</Button>
                    <Button type='default' style={{ borderRadius:'0 6px 6px 0'}} onClick={()=>{submitFun('','','deletes')}}>删除</Button>
                </div>
            </div>
            {msgTitle}
            {contextHolder}
            <Table
                rowSelection={rowSelection}
                columns={columns}
                key={content.id}
                rowKey='id'
                style={{height: 'calc(100% - 100px)'}}
                dataSource={tableData}
                scroll={{ x: 'max-content', y: tableHeight}}

            />
            <Modal title={modalTitle}
                   open={isModalOpen}
                   width={500}
                   onOk={()=> {onFinish()}}
                   onCancel={()=>{setIsShowModal(false);}}>
                <Form
                    name="basic"
                    layout='inline'
                    style={{
                        alignItems: 'center', // 垂直居中
                        rowGap: 16            // 行间距
                    }}
                    initialValues={{ remember: true }}
                    labelCol={{span:5}}
                    autoComplete="off"
                    form={formRef}
                >
                    <Form.Item label="详细名称" className='w-11/12'  name="name" rules={[{ required: true, message: '字段不能为空!' }]}>
                        <Input  />
                    </Form.Item>
                    <Form.List name="itemList" className='w-11/12' initialValue={['']}>
                        {(fields, { add, remove }) => (
                            <div className="flex flex-col w-full justify-center"  style={{rowGap: 16}}>
                                {fields.map(({ key, name, ...restField }) => (
                                  <div className='flex items-center w-11/12'  key={key}>
                                      <Form.Item
                                          className='w-full'
                                          {...restField}
                                          name={name}
                                          label={`选项 ${name + 1}`}
                                          rules={[{ required: true, message: '选项不能为空' }]}
                                      >
                                          <Input className='w-full' placeholder="请输入选项内容" />
                                      </Form.Item>

                                      {/* 删除图标（至少保留一项） */}
                                      {fields.length > 1 && (
                                          <MinusCircleOutlined
                                              className="dynamic-delete-button"
                                              style={{ marginLeft: 8, color: '#ff4d4f' }}
                                              onClick={() => remove(name)}
                                          />
                                      )}
                                  </div>
                                ))}

                                {/* 添加按钮 */}
                                <Form.Item>
                                    <Button
                                        type="dashed"
                                        onClick={() => add()}
                                        icon={<PlusOutlined />}
                                        style={{marginLeft: '88px'}}
                                    >
                                        添加选项
                                    </Button>
                                </Form.Item>
                            </div>
                        )}
                    </Form.List>
                   <Form.Item label="排序" className='w-11/12' name="sort" rules={[{ required: true, message: '字段不能为空!' }]}>
                       <InputNumber className='w-full' />
                   </Form.Item>
                    <Form.Item name="type" className='w-11/12' label="类型" rules={[{ required: true, message: '字段不能为空!' }]}>
                        <Radio.Group
                            options={typeList}
                        />
                    </Form.Item>
                </Form>
            </Modal>

        </div>
    )
}
export default Home